import { FileItem, RequestOption, UploadRequest } from '@arco-design/web-vue/es/upload'
import { FUNDFLOW_CREATE, UPLOAD_SCREENSHOTS, } from '@/api/flow'
import { CUSTOMER_LIST } from '@/api/customer'
import { request, ResponseCode } from '@/api/request'
import { Customer } from '@/api/customer/type'
import { Message } from '@arco-design/web-vue'
import { useUser } from '@/views/system/user.hook'
import type { User } from '@/api/type'

export const useFlowActionHook = ({
  doRefresh
}: {
  doRefresh: () => void
}) => {
  const { getUserList } = useUser()

  const formRef = ref()

  const customers = ref<Customer[]>([])

  const managerName = ref<String>()
  const managers = ref<User[]>([])

  const form = reactive({
    accountManager: '',
    actualPaymentAmount: 0,
    advancePaymentAmount: 0,
    customerId: undefined,
    paymentBank: '',
    paymentScreenshot: [] as FileItem[],
    rechargeAmount: 0,
    remarks: '',
    status: 1,
  })

  const modalProps = reactive({
    loading: false,
  })

  const paymentScreenshot = computed(() => form.paymentScreenshot.at(0))

  const selectCustomer = computed(() => customers.value.find(c => c.customerId === form.customerId))

  const uploadScreenShots = (option: RequestOption): UploadRequest => {
    const { fileItem, onSuccess, onError, onProgress } = option
    if (fileItem.file) {
      const formData = new FormData()
      formData.append('file', fileItem.file)
      request.Post<Response>(UPLOAD_SCREENSHOTS, formData, {
        enableDownload: true
      }).then(res => res.json()).then(({ code, message, body }) => {
        if (code === ResponseCode.SUCCESS) {
          onSuccess(body)
        } else {
          onError(message)
        }
      })
    }

    return {}
  }

  const getCustomers = async () => {
    if (customers.value.length) return
    const { code, body } = await request.Post<Response>(CUSTOMER_LIST).then(res => res.json())
    if (code === ResponseCode.SUCCESS) {
      customers.value = body
    }
  }

  const getManagers = async () => {
    if (managers.value.length) return
    const { code, body } = await getUserList({ pageNo: 1, pageSize: 50, userName: managerName.value })
    if (code === ResponseCode.SUCCESS) {
      console.log('getManagers', body)
      managers.value = body
    }
  }

  const init = () => {
    getCustomers()
    getManagers()
  }

  const submit = async (done: (closed: boolean) => void): Promise<boolean | void> => {
    console.log(`submit`, done)
    if (modalProps.loading) return
    modalProps.loading = true
    const err = await formRef.value?.validate()
    if (err) return (modalProps.loading = false)
    const { code, message } = await request
      .Post<Response>(FUNDFLOW_CREATE, {
        ...form,
        customerName: selectCustomer.value?.customerName,
        paymentScreenshot: paymentScreenshot.value?.response,
      })
      .then((res) => res.json())

    if (code === ResponseCode.SUCCESS) {
      done(true)
      return doRefresh()
    } else {
      done(false)
      Message.error(message)
      return false
    }
  }

  onMounted(init)

  return {
    form,
    formRef,
    submit,
    managers,
    customers,
    modalProps,
    paymentScreenshot,
    selectCustomer,
    uploadScreenShots,
  }
}
